var express = require('express');
var router = express.Router();
let { studentModul, TitleModul } = require('../modul/modul')
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});


// 获取学生信息
router.get("/student/list", async (req, res) => {
  let data = await studentModul.find()
  res.send({ data })
})

// 获取学生信息及对应面试题
router.get("/student/title", async (req, res) => {
  let data = await studentModul.aggregate([
    {
      $lookup: {
        from: "Title",
        localField: "_id",
        foreignField: "studentID",
        as: "title"
      }
    }
  ])

  let title = await TitleModul.find()
  data.map(stuItem => {
    id = String(stuItem._id)
    title.map(TitleItem => {
      if (String(TitleItem.studentID) == id) {
        // TitleItem.key = TitleItem.studentID
        stuItem.title.push(TitleItem)
      }
    })
  })
  res.send({ data })
})


/* 
展示信息 
搜索+分页
*/
router.get("/student/info", async (req, res) => {
  // 分页条件
  let pagesize = req.query.pagesize
  let currentPage = req.query.currentPage
  let total = 0

  // 根据名字和面试题搜索
  let name = req.query.name
  let title = req.query.title
  // console.log(name,title,"11111");
  let regName = new RegExp(name)
  let regTitle = new RegExp(title)

  let data = []
  data = await TitleModul.find().populate("studentID").limit(pagesize).skip((currentPage - 1) * pagesize)

  if (name && !title) {
    data = await TitleModul.find({ name: regName }).limit(pagesize).skip((currentPage - 1) * pagesize)
    total = await TitleModul.find({ name: regName }).count()
  }
  if (!name && title){
    data = await TitleModul.find({title:regTitle}).limit(pagesize).skip((currentPage-1) * pagesize)
    total = await TitleModul.find({title:regTitle}).count()
  }

  res.send({
    data,
    code:200,
    mes:"成功展示信息",
    total
  })
})

module.exports = router;
